<?php
/**
 * Created by PhpStorm.
 * User: boye009
 * Date: 2016/3/11
 * Time: 15:27
 */

namespace app\index\domain;

use app\index\domain\BaseDomain;
use app\admin\api\FreightTemplateApi;
use app\shop\api\ProductApi;
use app\shop\api\ProductImageApi;
use app\shop\api\ProductSkuApi;
use app\shop\api\OrdersApi;
use app\shop\api\StoreApi;
use app\shop\api\ProductAttrApi;
use app\shop\api\ProductGroupApi;
use app\shop\api\ShoppingCartApi;
use app\shop\api\ProductPackageApi;
use app\shop\api\ProductPackageItemApi;

class ShoppingCartDomain extends BaseDomain{

    protected $business_code = "shopping";

    //修改商品
    public function edit(){
        $this -> checkVersion($this->api_ver);
        $notes = "应用".$this->client_id."，调用购物车批量修改接口";
        addLog("ShoppingCart/edit",$_GET,$_POST,$notes);

        if(IS_POST){
            $uid   = $this -> _post('uid',0,'缺少uid参数');
            $id    = $this -> _post('id','','缺少购物车id参数');
            $count = $this -> _post('count','','缺少数量参数');

            $id    = array_unique(explode(',',$id));
            $count = explode(',',$count);
            $res   = "";
            if(count($id) != count($count)) return $this->apiReturnErr('参数不匹配');
            //不允许含有套餐商品
            $r = apiCall(ShoppingCartApi::GET_INFO,[['_string'=>'id in ('.implode(',', $id).') and package_id <> 0']]);
            if(!$r['status']) return $this->apiReturnErr($r['info']);
            if(!empty($r['info'])) return $this->apiReturnErr('不允许直接修改套餐商品');
            foreach($id as $k => $v){
                //购物车检查 - 限购 - 库存 - 分组信息合法性
                $r = apiCall(ShoppingCartApi::CHECK_ID,[$v,$count[$k],false]);
                if(!$r['status']) $this->apiReturnErr($r['info']);
                $map    = ['id' => $v];
                $entity = ['count' => $count[$k]];
                $result = apiCall(ShoppingCartApi::SAVE,[$map,$entity]);
                if($result['status']){
                    $res = $res.$v.',';
                }else{
                    $this -> apiReturnErr("发生错误".$result['info']."未完全修改！已修改".$res);
                }

            }
            $this -> apiReturnSuc('修改成功！');

        }

    }

    //添加商品进购物车 - 生成购物车
    public function add(){
        $this->checkVersion(101);
        $notes = "应用".$this->client_id."，调用购物车添加接口";
        addLog("ShoppingCart/add",$_GET,$_POST,$notes);

        $uid        = $this -> _post('uid',0,'用户id缺失');
        $p_ids      = $this -> _post('pid',0,'商品id缺失');
        $counts     = $this -> _post('count',0,'商品数量缺失');
        $psku_ids   = $this -> _post('psku_id',0,'规格id缺失');
        $group_id   = $this -> _post('group_id',0); //分组ID
        $package_id = $this -> _post('package_id',0); //套餐ID

        $group_id = intval($group_id);
        if($group_id < 0)  $this ->apiReturnErr('商品分组ID有误');
        $package_id = intval($package_id);
        if($package_id < 0) $this ->apiReturnErr('商品套餐ID有误');
        $p_ids    = array_unique(explode(',', $p_ids));
        $counts   = explode(',', $counts);
        $psku_ids = explode(',', $psku_ids);
        if(count($p_ids) != count($counts) || count($p_ids) != count($psku_ids))
            $this->apiReturnErr('参数不匹配');
        if($package_id){
            $group_id = 0;
            //是否全属于该套餐 - 并验证套餐状态
            $r = apiCall(ProductPackageItemApi::CHECK,[$p_ids,$psku_ids,$package_id]);
            if(!$r['status']) $this->apiReturnErr($r['info']);
        }
        $ids = [];
        $now = time(); //每次套餐时间统一
        $model = new \think\model\Adv();
        $model ->startTrans();
        foreach ($p_ids as $k=>$p_id) {
            $id      = 0;
            $count   = $package_id ? 1:$counts[$k]; //套餐每次购买一件
            $psku_id = $psku_ids[$k];
            $map     = ['id' => $p_id];
            $r       = apiCall(ProductApi::GET_INFO,[$map]);
            $this->checkApiReturn($r,false,'商品错误',$model);
            $store_id    = $r['info']['store_id'];
            $name        = $r['info']['name'];
            $template_id = $r['info']['template_id'];
            $weight      = $r['info']['weight'];

            $map = ['id' => $template_id];
            $r   = apiCall(FreightTemplateApi::GET_INFO,[$map]);
            $this->checkApiReturn($r,false,'请联系商家检查商品运费模板',$model);

            //查询该规格会员价
            $r = apiCall(ProductSkuApi::GET_INFO_BY_USER,[$uid,$psku_id]);
            $this->checkApiReturn($r,false,false,$model);
            if(!empty($r['info']) && $r['info']['product_id'] == $p_id){
                $sku_id    = $r['info']['sku_id'];
                $sku_desc  = $r['info']['sku_desc'];
                $price     = $r['info']['price'];
                $ori_price = $r['info']['ori_price'];
                $icon_url  = $r['info']['icon_url'];
            }else{
                $model ->rollback();
                $this -> apiReturnErr("商品规格有误");
            }

            if(empty($icon_url)){
                $map = [
                    'pid' => $p_id,
                    'type'=> 6015,//主图
                ];
                $r = apiCall(ProductImageApi::GET_INFO,[$map]);
                $this->checkApiReturn($r,false,'pid错误',$model);
                $icon_url = $r['info']['img_id'];
            }

            //查询该规格活动价-验证分组
            if($group_id){
                $r = apiCall(ProductGroupApi::GET_INFO,[['p_id'=>$p_id,'g_id'=>$group_id,'sku_id'=>$psku_id]]);
                $this->checkApiReturn($r,false,false,$model);
                if(!empty($r['info'])){
                    if($r['info']['end_time']<$now || $r['info']['start_time']>$now)
                    $this->apiReturnErr('分组未生效');
                    $price = $r['info']['price'];
                }
            }
            //该用户购物车 是否存有该商品该规格该分组 或 该商品该套餐 的商品
            if($package_id){
                //直接添加 (存在规格冲突)
                // $map = [
                //     'uid'        => $uid,
                //     'p_id'       => $p_id,
                //     'package_id' => $package_id,
                // ];
                //购物车检查 - 限购 - 库存
                $r = apiCall(ProductSkuApi::CHECK_SKUID,[$uid,$psku_id,$count,false]);
            }else{
                $map = [
                    'uid'        => $uid,
                    'p_id'       => $p_id,
                    'psku_id'    => $psku_id,
                    'group_id'   => $group_id,
                ];
                $r   = apiCall(ShoppingCartApi::GET_INFO,[$map]);
                $this->checkApiReturn($r,false,false,$model);
                if(!empty($r['info'])){
                    $id        = intval($r['info']['id']);
                    $ori_count = $r['info']['count'];
                    $count     = intval($count) + intval($ori_count);
                    //购物车检查 - 限购 - 库存
                    $r = apiCall(ShoppingCartApi::CHECK_ID,[$id,$count,false]);
                }else{
                    //购物车检查 - 限购 - 库存
                    $r = apiCall(ProductSkuApi::CHECK_SKUID,[$uid,$psku_id,$count,false]);
                }
            }
            $this->checkApiReturn($r,false,false,$model);
            //获取该规格税费
            $r = apiCall(ProductSkuApi::GET_TAX,[$p_id,$psku_id]);
            $this->checkApiReturn($r,false,false,$model);
            $tax = floatval($r['info']);
            $entity = [
                'uid'         => $uid,
                'store_id'    => $store_id,
                'p_id'        => $p_id,
                'sku_id'      => $sku_id,
                'sku_desc'    => $sku_desc,
                'icon_url'    => $icon_url,
                'count'       => $count,
                'name'        => $name,
                'express'     => 0.0, //总运费 - 订单再计算
                'template_id' => $template_id,
                'group_id'    => $group_id,
                'price'       => $price,
                'ori_price'   => $ori_price,
                'psku_id'     => $psku_id,
                'weight'      => $weight,
                'package_id'  => $package_id,
                'tax_rate'    => $tax,//该规格单件税费，税率xvip1价格(为0将使用原价)
                'update_time' => $now,
            ];
            if(0 === $id){
                $entity['create_time'] = $now;
                $r  = apiCall(ShoppingCartApi::ADD,[$entity]);
                $id = $r['info'];
            }else{
                $r = apiCall(ShoppingCartApi::SAVE_BY_ID,[$id,$entity]);
            }
            $this->checkApiReturn($r,false,false,$model);
            $ids[] = $id;
        }
        $model ->commit();
        $this -> apiReturnSuc(['cart_ids'=>$ids,'msg'=>($package_id ? '套餐':($group_id ? '活动':'').'商品').'添加'.'成功']);
    }

    public function count(){
        $this->checkVersion($this->api_ver);
        $notes = "应用".$this->client_id."，调用购物车对应商品数量接口";
        addLog("ShoppingCart/count",$_GET,$_POST,$notes);

        if(IS_POST){

            $psku_id = $this -> _post('psku_id',0,"商品规格id缺失");
            $map = ['id' => $psku_id];

            $result = apiCall(ProductSkuApi::GET_INFO,array($map));
            if($result['status']){
                $pcount = $result['info']['quantity'];
                if($pcount === NULL){
                    $this -> apiReturnErr("规格参数错误");
                }
                $this -> apiReturnSuc($pcount);
            }else{
                $this -> apiReturnErr($result['info']);
            }
        }

    }

    //全部购物车
    public function all(){
        $this->checkVersion(101);
        $notes = "应用".$this->client_id."，调用购物车不分页查询接口";
        addLog("ShoppingCart/all",$_GET,$_POST,$notes);

        if(IS_POST){
            $uid       = $this -> _post('uid',0,'用户id缺失');
            // $page_no   = $this -> _post('page_no',1);
            // $page_size = $this -> _post('page_size',10);
            $map = ['uid' => $uid];
            // $page   = ['curpage'=>$page_no,'size'=>$page_size]; //分页查询
            // $order  = "store_id desc,update_time desc";
            $order  = "create_time desc";
            $result = apiCall(ShoppingCartApi::QUERY_NO_PAGING,[$map,$order]);
            if($result['status']){
                $stores = [];
                $stores_list = [];
                $packs  = [];
                $packs_info = [];
                $all    = [];
                $list   = $result['info'];

                // $list  = $result['info']['list'];
                // $count = $result['info']['count'];
                // trace('ShoppingCartDomain.php');
                if(is_array($list)){
                    foreach($list as $k=>&$v){
                        $pack_id = intval($v['package_id']);
                        //检查库存 - 限购
                        $r = apiCall(ShoppingCartApi::CHECK_ID,[$v['id'],0,true]);
                        $v['error'] = '';
                        if(!$r['status']) $v['error'] = $r['info'];
                        if($pack_id){
                            $packs[$pack_id][$v['create_time']]['carts'][] = $v;
                            $packs_info[$pack_id][$v['create_time']]['pid'][] = $v['p_id'];
                            $packs_info[$pack_id][$v['create_time']]['skuid'][] = $v['sku_id'];
                        }else{
                            $stores[] = $v['store_id'];
                            $stores_list[] = $v;
                        }
                        // $vo['icon_url'] = getImageUrl($vo['icon_url']);
                        // trace($vo);
                    }
                    //检查套餐完整性
                    foreach ($packs as $k=>&$v) { //package_id //套餐列表
                      //查询套餐信息
                      $r = apiCall(ProductPackageApi::GET_INFO,[['id'=>$k]]);
                      if(!$r['status']) return $this->apiReturnErr($r['info']);
                      $rinfo = empty($r['info']);
                      foreach ($v as $kk=>$vv) { //create_time
                        // trace('==='.$kk);
                        // trace($v);
                        // trace($vv);
                        $pids = [];
                        $pskuids = [];
                        foreach ($vv['carts'] as $kkk => $vcart) {
                            $pids[]    = $vcart['p_id'];
                            $pskuids[] = $vcart['psku_id'];
                        }
                        $error     = '';
                        $res = apiCall(ProductPackageItemApi::CHECK,[$pids,$pskuids,$k]);
                        unset($pids);unset($pskuids);
                        if(!$res['status']) $error = $res['info'];
                        foreach ($vv['carts'] as $kkk => $vcart) {
                            $v[$kk]['id']    = $k;//$rinfo ? $k:$r['info']['id'];
                            $v[$kk]['name']  = $rinfo ? '搭配套餐':$r['info']['package_name'];
                            $v[$kk]['create_time'] = $rinfo ? '':$r['info']['create_time'];
                            $v[$kk]['end_time']    = $rinfo ? '':$r['info']['end_time'];
                            $v[$kk]['price'] = $rinfo ? '':$r['info']['package_price'];
                            $v[$kk]['error'] = $rinfo ? '套餐已失效':'';
                        }
                      }
                    }
                    $new_packs = [];
                    foreach ($packs as $v) {
                        foreach ($v as $vv) {
                            $new_packs[] = $vv;
                        }
                    }
                    unset($packs);
                    unset($packs_info);
                    //
                    $stores = array_unique($stores);
                    foreach ($stores as $v) {
                        $r = apiCall(StoreApi::GET_INFO_WITH_DISCOUNT,[$v]);
                        if(!$r['status']) $this->apiReturnErr($r['info']);
                        $all[$v] = $r['info'];
                    }
                    unset($stores);
                    foreach ($stores_list as $v) {
                        $store_id = $v['store_id'];
                        $all[$store_id]['carts'][] = $v;
                    }
                    $this->apiReturnSuc(['store_list'=>array_values($all),'pack_list'=>$new_packs]);
                }else{
                    $this->apiReturnSuc([]);
                }
            }else{
                $this -> apiReturnErr($result['info']);
            }

        }
    }
    /**
     * 分页查询 - 废弃
     * @return [type] [description]
     */
    public function query(){
        $this->apiReturnErr('接口以废弃');
        // $this->checkVersion($this->api_ver);
        // $notes = "应用".$this->client_id."，调用购物车分页查询接口";
        // addLog("ShoppingCart/query",$_GET,$_POST,$notes);

        // if(IS_POST){
        //     $uid       = $this -> _post('uid',0,'用户id缺失');
        //     $page_no   = $this -> _post('page_no',0);
        //     $page_size = $this -> _post('page_size',10);
        //     $map = ['uid' => $uid];

        //     $page   = ['curpage'=>$page_no,'size'=>$page_size]; //分页查询
        //     $order  = "store_id desc,update_time desc";
        //     $result = apiCall(ShoppingCartApi::QUERY,[$map,$page,$order]);
        //     if($result['status']){
        //         $list  = $result['info']['list'];
        //         $count = $result['info']['count'];
        //         // trace('ShoppingCartDomain.php');
        //         if(is_array($list)){
        //             foreach($list as $k=>&$vo){
        //                 $r = apiCall(ShoppingCartApi::CHECK_ID,[$vo['id'],0,true]);
        //                 $vo['error'] = '';
        //                 if(!$r['status']) $vo['error'] = $r['info'];
        //                 // $vo['icon_url'] = getImageUrl($vo['icon_url']);
        //                 // trace($vo);
        //             }
        //         }
        //         $this->apiReturnSuc(['count'=>$count,'list'=>$list]);
        //     }else{
        //         $this -> apiReturnErr($result['info']);
        //     }

        // }
    }
    //查看单个购物车
    public function getInfo(){
        $this->checkVersion(101);
        $notes = "应用" . $this->client_id . "，调用单个购物车查询接口";
        addLog("ShoppingCart/getInfo", $_GET, $_POST, $notes);

        $id  = $this -> _post('id',0,"缺少购物车id参数");
        $map = ['id' => $id];
        //查询购物车信息
        $result = apiCall(ShoppingCartApi::GET_INFO,[$map]);
        if($result['status']){
            $info = $result['info'];
            if(!empty($info)){
                //查询店铺信息 
                $r = apiCall(StoreApi::GET_INFO_WITH_DISCOUNT,[$info['store_id']]);
                if(!$r['status']) $this->apiReturnErr($r['info']);
                if(empty($r['info'])) $this->apiReturnErr('店铺错误');
                $result = apiCall(ShoppingCartApi::CHECK_ID,[$id,0,true]);
                $info['error'] = '';
                if(!$result['status']) $info['error'] = $result['info'];
                $r['info']['carts'] = $info;
                // $info['icon_url'] = getImageUrl($info['icon_url']);
                $this->apiReturnSuc($r['info']);
            }else{
                $this->apiReturnErr("查询失败");
            }

        }else{
            $this->apiReturnErr("查询失败");
        }

    }

    //删除购物车 - 可同时删除任意个套餐
    public function delete(){

        $this->checkVersion($this->api_ver);
        $notes = "应用" . $this->client_id . "，调用购物车删除接口";
        addLog("ShoppingCart/delete", $_GET, $_POST, $notes);
        // if(true)  $this -> apiReturnSuc('删除成功');

        $id  = $this -> _post('id',0,'缺少购物车id');
        $uid = $this -> _post('uid',0,'缺少uid');
        $id  = array_unique(explode(',',$id));
        $id_count    = count($id);
        // $pa_count    = 0;
        $package     = [];
        $create_time = 0;
        // 若含套餐商品,是否包含整个套餐
        $r = apiCall(ShoppingCartApi::QUERY_NO_PAGING,[['_string'=>'id in ('.implode(',', $id).') ','uid'=>$uid],false,'id,create_time,update_time,p_id,package_id,psku_id']);
        if(!$r['status'])     return $this->apiReturnErr($r['info']);
        if(empty($r['info'])) return $this->apiReturnErr('uid或id错误');
        foreach ($r['info'] as $v) {
            $p = intval($v['package_id']);
            if($p>0){
                //套餐商品数+1
                // $pa_count++;
                //套餐分批次
                $package[$p][$v['create_time']][$v['p_id']] = ['pid'=>$v['p_id'],'psku_id'=>$v['psku_id']];
            }
        }
        foreach ($package as $k=>$v) {
            //检查同一批次套餐的个数
            $r = apiCall(ProductPackageItemApi::QUERY_NO_PAGING,[['package_id'=>$k]]);
            if(!$r['status']) return $this->apiReturnErr($r['info']);
            $count = count($r['info']);
            foreach ($v as $vv) {
                //TODO: 严格检测
                if(count($vv) !== $count) return $this->apiReturnErr('只能同时删除整个套餐');
            }
        }
        if($id){
            $map = ['_string'=>'id in ('.implode(',', $id).')'];
            $r   = apiCall(ShoppingCartApi::DELETE,[$map]);
            if($r['status']){
                $this -> apiReturnSuc('删除成功');
            }else{
                $this -> apiReturnErr($r['info']);
            }
        }else{
            $this->apiReturnErr('id错误');
        }
    }

    /**
     * [checkApiReturn description] domain专用
     * @author rainbow
     * @param  [type]  $result  [description]
     * @param  string  $err     [description]
     * @param  string  $nullerr [description]
     * @param  boolean $model   事务对象
     * @param  string  $fullerr [description]
     * @return [type]           [description]
     */
    private function checkApiReturn($result,$err=false,$nullerr=false,$model=false,$fullerr=false)
    {
        if(false === $result['status']){
            if(false === $err) $err = $result['info'];
            if(false !== $model) $model->rollback();
            $this->apiReturnErr($err);
        }else{
            if(false !== $nullerr && empty($result['info'])){
                if(false !== $model) $model->rollback();
                $this->apiReturnErr($nullerr);
            }
            if(false !== $fullerr && !empty($result['info'])){
                if(false !== $model) $model->rollback();
                $this->apiReturnErr($fullerr);
            }
        }
    }
}